import hilog from '@ohos.hilog'

export class ArrayManager {
  static clear<T>(arr: T[]) {
    arr.splice(0, arr.length);
  }

  //foreach不是同步的,这里用同步的方法去遍历.
  static mapSync<T, R>(arr: T[], handler: (item: T, index: number) => R): R[] {
    let resultArr: R[] = [];
    //length为undefined报错,并不执行后面的代码,导致界面进度条卡死.
    for (let i = 0; i < arr?.length ?? 0; i++) {
      let item = arr[i];
      resultArr.push(handler(item, i))
    }
    return resultArr;
  }

  static enumerateSync<T>(arr: T[], handler: (item: T, index: number) => void) {
    for (let i = 0; i < arr.length; i++) {
      let item = arr[i];
      handler(item, i)
    }
  }

  static indexOfItem<T>(arr: T[], item: T): number {
    let index = arr.findIndex((value) => {
      return (value === item);
    })
    return index;
  }

  static removeItem<T>(arr: T[], deleteItem: T) {
    let index = ArrayManager.indexOfItem(arr, deleteItem);
    if (index != -1) {
      arr.splice(index, 1);
    }
  }

  static removeMatch<T>(arr: T[], filter: (T) => boolean): T[] {
    let index = arr.findIndex((value) => {
      return filter(value)
    })
    if (index != -1) {
      arr.splice(index, 1);
    }
    return arr
  }

  static getLastItem<T>(arr: T[]): T | null {
    if (arr.length > 0) {
      return arr[arr.length - 1];
    }
    else {
      return null;
    }
  }
}